const express = require('express');
const router = express.Router();
// const logger = require('../logger/logger');
var fs = require('fs');
var multer = require('multer'); // v1.0.5
var path = require('path')

var createFolder = function(folder){
   try{
      fs.exists(folder, function(exists) {
          if(exists){
             fs.accessSync(folder); 
          }else{
            fs.mkdirSync(folder);
            fs.accessSync(folder); 
          }
        });
    }catch(e){
        
        fs.mkdirSync(folder);
    }  
};

var uploadFolder = './file/';

createFolder(uploadFolder);

// 通过 filename 属性定制
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder);    // 保存的路径，备注：需要自己创建
    },
    filename: function (req, file, cb) {
        console.log(file)
        file.originalname.split(".")[1]
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        cb(null, file.fieldname + '-' + Date.now()+'.'+file.originalname.split(".")[1]);  
    }
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })


//view file
router.get('/file/:filename', function(req, res){
    var filename = req.params.filename
    var configPath = './file/'+filename;
    var contentType = {
          "css": "text/css",
          "gif": "image/gif",
          "html": "text/html",
          "ico": "image/x-icon",
          "jpeg": "image/jpeg",
          "jpg": "image/jpeg",
          "js": "text/javascript",
          "json": "application/json",
          "pdf": "application/pdf",
          "png": "image/png",
          "svg": "image/svg+xml",
          "swf": "application/x-shockwave-flash",
          "tiff": "image/tiff",
          "txt": "text/plain",
          "wav": "audio/x-wav",
          "wma": "audio/x-ms-wma",
          "wmv": "video/x-ms-wmv",
          "xml": "text/xml"
        }
    //设置请求的返回头type,content的type类型列表见上面
    res.setHeader("Content-Type", contentType);
    //格式必须为 binary 否则会出错
    var content =  fs.readFileSync(configPath,"binary");   
    res.writeHead(200, "Ok");
    res.write(content,"binary"); //格式必须为 binary，否则会出错
    res.end();
});



//upload file  ： file 为前端标签的name值
router.post('/upfile/:filename',upload.single('file'), function(req, res){
    var file = req.file;
    console.log(file);
    res.send({code: '200',filename:file.filename});

});



module.exports = router;
